package com.chong.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/hello")
public class ConsumeController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/consume1")
    public String helloWorld(String s) {
        System.out.println("传入的值为： " + s);
        // 第一种调用方式
        String forObject = new RestTemplate().getForObject("http://localhost:8701/hello/world?s=" + s,String.class);
        return forObject;
    }

    @RequestMapping("/consume2")
    public String helloWorld2(String s) {
        System.out.println("传入的值为： " + s);
        // 第二种调用方式
        // 根据服务名，获取服务列表，根据算法获取某个服务，并访问某个服务的网络位置
        ServiceInstance serviceInstance= loadBalancerClient.choose("EUREKA-SERVICE");
        String forObject = new RestTemplate().getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/hello/world?s="+s,String.class);
        return forObject;
    }


    @RequestMapping("/consume3")
    public String helloWorld3(String s) {
        System.out.println("传入的值为： " + s);
        // 第三种通过restTemplate注入的方式
        String forObject = restTemplate.getForObject("http://localhost:8701/hello/world?s=" + s,String.class);
        return forObject;
    }
}
